import AppDataSource from "@/common/database";
import { Hono } from "hono";
import { z } from "zod";
import { User } from "@/models/User";
import { HTTPException } from "hono/http-exception";
import { Store } from "@/models/Store";

const userRoute = new Hono();

const querySchema = z.object({
  pageNum: z.number().min(1).default(1),
  pageSize: z.number().min(1).max(100).default(10),
});

userRoute.get("/list", async (c) => {
  let query = c.req.query();
  let parseQuery = querySchema.safeParse(query);

  let userList = await AppDataSource.manager.find(User, {
    skip: (parseQuery.data.pageNum - 1) * parseQuery.data.pageSize,
    take: parseQuery.data.pageSize,
  });

  return c.json({ code: 200, message: "success", data: userList });
});

let bodySchema = z.object({
  username: z.string().min(11),
  password: z.string().min(6),
  name: z.string(),
  storeId: z.coerce.number(),
});

userRoute.post("/add", async (c) => {
  let body = await c.req.parseBody();

  let parseBody = bodySchema.safeParse(body);

  if (!parseBody.success) {
    let message = parseBody.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let store = await AppDataSource.manager.findOneBy(Store, {
    id: parseBody.data.storeId,
  });

  let user = new User();
  user.username = parseBody.data.username;
  user.password = parseBody.data.password;
  user.name = parseBody.data.name;
  user.store = store;

  try {
    await user.save();
  } catch (error) {
    throw new HTTPException(400, { message: error.message });
  }

  return c.json({ code: 200, message: "success", data: user });
});

let updateSchema = z.object({
  id: z.coerce.number(),
  username: z.string().min(11),
  name: z.string(),
  storeId: z.coerce.number(),
});

userRoute.post("/update", async (c) => {
  let body = await c.req.parseBody();

  let parseBody = updateSchema.safeParse(body);

  if (!parseBody.success) {
    let message = parseBody.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let store = await AppDataSource.manager.findOneBy(Store, {
    id: parseBody.data.storeId,
  });
  let user = await User.findOne({ where: { id: parseBody.data.id } });

  user.username = parseBody.data.username;
  user.name = parseBody.data.name;
  user.store = store;

  try {
    await user.save();
  } catch (error) {
    throw new HTTPException(400, { message: error.message });
  }

  return c.json({ code: 200, message: "success", data: user });
});

let delUserSchema = z.object({
  id: z.coerce.number(),
});

userRoute.post("/del", async (c) => {
  let body = await c.req.parseBody();

  let parseBody = delUserSchema.safeParse(body);
  if (!parseBody.success) {
    let message = parseBody.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  try {
    let user = await User.findOne({ where: { id: parseBody.data.id } });

    if (!user) {
      throw new HTTPException(400, { message: "用户不存在" });
    }

    await user.softRemove();

    return c.json({ code: 200, message: "success", data: user });
  } catch (error) {
    throw new HTTPException(400, { message: error.message });
  }
});

export default userRoute;
